﻿using System;
using System.Web;
using System.Web.Helpers;
using System.Web.WebPages;
using WebMatrix.WebData;

namespace Account
{
    /// <summary>
    /// Summary description for Confirm
    /// </summary>
    public static class ForgotPassword
    {
        public class Model
        {
            public string Email { get; set; }
        }

        public class Error
        {
            public ErrorMessage Email { get; set; }

            public Error()
            {
                Email = ErrorMessage.Nil;
            }
        }  

        public static void Init(WebPageBase web)
        {
            Model model = web.Page.Model = new Model();
            Error error = web.Page.Errors = new Error();

            web.Page.IsReadonly = false;
                        
            model.Email = web.Request.Form["email"] ?? web.Request.QueryString["email"];

            if (web.IsPost)
            {
                var resetToken = string.Empty;
                // validate email
                if (model.Email.IsEmpty() || !model.Email.Contains("@"))
                {
                    error.Email = web.Error("Please enter a valid email");
                }
                if (web.Page.IsValid)
                {
                    if (WebSecurity.GetUserId(model.Email) > -1 && WebSecurity.IsConfirmed(model.Email))
                    {
                       resetToken = WebSecurity.GeneratePasswordResetToken(model.Email); //Optionally specify an expiration date for the token
                    }
                    else
                    {
                        web.Page.IsValid = false;
                        web.Page.IsReadonly = true;
                    }
                }
                if (web.Page.IsValid)
                {
                    var hostUrl = web.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                    var resetUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/PasswordReset?resetToken=" + HttpUtility.UrlEncode(resetToken));
                    WebMail.Send(
                        to: model.Email,
                        subject: "Please reset your password",
                        body: "Use this password reset token to reset your password. The token is: " + resetToken + @". Visit <a href=""" + resetUrl + @""">" + resetUrl + "</a> to reset your password."
                    );
                    web.Page.IsReadonly = true;                    
                }
            }
        }
    }
}